//
//  BaseRealm.swift
//  MySwiftObject
//
//  Created by anscen on 2022/5/27.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
import RealmSwift

fileprivate let base = BaseRealm()
class BaseRealm: NSObject {
    fileprivate lazy var path : String? = {
        let path = NSHomeDirectory() + "/Documents/Caches/Realm/"
        let file = FileManager.default
        if file.fileExists(atPath: path) == false{
            guard let _ = try? file.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) else { return nil }
        }
        return path + "default.realm"
    }()
    lazy var realm: Realm? = {
        //如果有新增字段，那么该字段的值必须＋1,内部会自动表结构升级不用开发者担心
        let dbversion : UInt64 = 14
        var config = Realm.Configuration(
          schemaVersion: dbversion,
          migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < dbversion) {

            }
        })
        Realm.Configuration.defaultConfiguration = config
        guard let url = path else { return nil }
        config.fileURL = URL(fileURLWithPath: url)
        let defaultRealm = try? Realm(configuration: config)
        return defaultRealm
    }()
}
class BBookRealm{
    fileprivate static func haveData(_ id :String) -> Bool{
        guard let realm = base.realm else {
            return false
        }
        let some = realm.objects(BBook.self).filter("bookId == '\(id)'")
        return some.count > 0 ? true : false
    }
    public static func insertData(_ dog :BBook){
        guard let realm = base.realm else {
            return
        }
        let haveData = haveData(dog.bookId)
        try? realm.write({
            if haveData{
                realm.add(dog, update: .all)
            }else{
                realm.add(dog)
            }
        })
    }
    public static func getData(_ id :String) ->BBook?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BBook.self).filter("bookId == '\(id)'")
        return some.first
    }
    public static func getDatas() ->[BBook]?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BBook.self)
        return some.reversed()
    }
    public static func deleteData(_ id :String){
        guard let realm = base.realm else {
            return
        }
        //删除某个之前需要先查询否则会闪退
        if let dog = getData(id){
            try? realm.write({
                realm.delete(dog)
            })
        }
    }
    public static func deleteAll(){
        guard let realm = base.realm else {
            return
        }
        try? realm.write({
            realm.deleteAll()
        })
    }
}
class BStudentRealm{
    //MARK:判断是否有数据
    fileprivate static func haveData(_ userId :String) -> Bool{
        guard let realm = base.realm else {
            return false
        }
        let some = realm.objects(BStudent.self).filter("studentId == '\(userId)'")
        return some.count > 0 ? true : false
    }
    //MARK:有就更新没有就增加
//    public static func insertData<T>(_ object :T){
//        guard let realm = base.realm else {
//            return
//        }
//        guard let _ = try? realm.write({
//            realm.add(object)
//        }) else { return }
//    }
//    public static func updateData<T :Object>(object :T.Type){
//        guard let realm = base.realm else {
//            return
//        }
//        guard let _ = try? realm.write({
//            realm.add(object, update: .all)
//        }) else { return }
//    }
    public static func insertData(_ user :BStudent){
        guard let realm = base.realm else {
            return
        }
        let haveData = haveData(user.studentId)
        guard let _ = try? realm.write({
            if haveData{
                realm.add(user, update: .all)
            }else{
                realm.add(user)
            }
        }) else { return }
    }
    //MARK:获取某一个数据
    public static func getData(_ userId :String) ->BStudent?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BStudent.self).filter("studentId == '\(userId)'")//.sorted(by: "user.userId", ascending: true)
        return some.first
    }
    //MARK:获取所有数据
    public static func getDatas() ->[BStudent]?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BStudent.self)
        return some.reversed()
    }
    //MARK:删除指定数据
    public static func deleteData(_ userId :String){
        guard let realm = base.realm else {
            return
        }
        if let user = getData(userId){
            try? realm.write({
                realm.delete(user)
            })
        }
    }
    //MARK:删除所有数据
    public static func deleteAll(){
        guard let realm = base.realm else {
            return
        }
        try? realm.write({
            realm.deleteAll()
        })
    }
}
class BStudent :Object{
    @Persisted var studentId :String
    @Persisted var name      :String
    @Persisted var book      :BBook? // 对一关系
    @Persisted var books     :List<BBook>//对多关系
    class override func primaryKey() -> String? {
        return "studentId"
    }
}
class BBook :Object{
    @Persisted var bookId    :String
    @Persisted var name      :String
    class override func primaryKey() -> String? {
        return "bookId"
    }
}
            
